/*******************************************************************************
 * Copyright (c) 2011 Grupo de Sistemas Inteligentes (GSI) - DIT UPM
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
package es.upm.dit.gsi.eclipse.jadex.adfmanager.wizards;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.core.runtime.*;
import org.eclipse.jface.operation.*;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.CoreException;
import java.io.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import es.upm.dit.gsi.eclipse.jadex.util.ImageFactory;

/**
 * Wizard for adding a new Expression to the selected agent
 *     
 * @author Pablo Muñoz
 * @TODO verify if the agent file exists in the current workspace
 */

public class AddExpressionWizard extends Wizard implements INewWizard {
	private AddExpressionWizardPage page;
	private ISelection selection;

	/**
	 * Constructor for Agent Wizard.
	 */
	public AddExpressionWizard(ISelection selection) {
		super();
		setNeedsProgressMonitor(true);
		setDefaultPageImageDescriptor(ImageFactory.getImageDescriptor(ImageFactory.GSI_BANNER_SMALL));
		this.selection = selection;
	}
	
	/**
	 * Adding the page to the wizard.
	 */
	public void addPages() {
		page = new AddExpressionWizardPage(selection);
		addPage(page);
	}

	/**
	 * This method is called when 'Finish' button is pressed in
	 * the wizard. We will create an operation and run it
	 * using wizard as execution context.
	 */
	public boolean performFinish() {
		final IFile agentFile = (IFile)((IStructuredSelection)selection).getFirstElement();
		
		final String type = page.getExpressionType();
		final String name = page.getExpressionName();
		final String _class = page.getExpressionClass();
		final String language = page.getExpressionLanguage();
		final String exported = page.getExpressionExported();
		final String description = page.getExpressionDescription();
		final String value = page.getExpressionValue();
		
		IRunnableWithProgress op = new IRunnableWithProgress() {
			public void run(IProgressMonitor monitor) throws InvocationTargetException {
				try {
					doFinish(agentFile, type, name, _class, language, exported, description,value,monitor);
				} catch (CoreException e) {
					throw new InvocationTargetException(e);
				} finally {
					monitor.done();
				}
			}
		};
		try {
			getContainer().run(true, false, op);
		} catch (InterruptedException e) {
			return false;
		} catch (InvocationTargetException e) {
			Throwable realException = e.getTargetException();
			MessageDialog.openError(getShell(), "Error", realException.getMessage());
			return false;
		}
		return true;
	}
	
	/**
	 * The worker method. It will find the container, create the
	 * file if missing or just replace its contents, and open
	 * the editor on the newly created file.
	 */
	private void doFinish(
			IFile agentFile,
			String type,
			String name,
			String _class,
			String language,
			String exported,
			String description,
			String value,
			IProgressMonitor monitor)
		throws CoreException {
		try{
			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
			Document doc = docBuilder.parse(agentFile.getRawLocation().toOSString());
		 
			//Get the capabilities element 
			Node expressions = doc.getElementsByTagName("expressions").item(0);
			
			Element newExpression = doc.createElement(type);
			newExpression.setAttribute("name", name);
			newExpression.setAttribute("class", _class);
			
			if(language != null){
				newExpression.setAttribute("language", language);
			}
			if(exported != null){
				newExpression.setAttribute("exported", exported);
			}
			if(description != null){
				newExpression.setAttribute("description", description);
			}
			newExpression.setTextContent(value);
			expressions.appendChild(newExpression);
		 
			//write the content into xml file
		    TransformerFactory transformerFactory = TransformerFactory.newInstance();
		    transformerFactory.setAttribute("indent-number", new Integer(4));
		    Transformer transformer;
			transformer = transformerFactory.newTransformer();
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		    DOMSource source = new DOMSource(doc);
		    StreamResult result =  new StreamResult(new File(agentFile.getRawLocation().toOSString()));
		    transformer.transform(source, result);
		    agentFile.refreshLocal(IFile.DEPTH_INFINITE, monitor);
			}
			catch(Exception e1){
				e1.printStackTrace();
			}
		    System.out.println("Done");
			monitor.worked(1);
	}

	/**
	 * We will accept the selection in the workbench to see if
	 * we can initialize from it.
	 * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
	 */
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		this.selection = selection;
	}
}